package com.code.zjm.location.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.code.zjm.location.R;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class LocationActivity extends AppCompatActivity implements LocationListener {
    private final static String TAG = LocationManager.class.getSimpleName();
    private LocationManager manager;
    private static final long MIN_TIME = 1000L * 5;
    private static final float MIN_DISTANCE = 10f;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
        manager = (LocationManager) getSystemService(LOCATION_SERVICE);

        System.out.println(manager.getProvider(LocationManager.GPS_PROVIDER));

        if (manager.getProvider(LocationManager.GPS_PROVIDER) != null || manager.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
            Log.i(TAG, "正在使用GPS 或者 网络进行定位");
            /*
             * 进行定位 provider:用于定位的locationProvider字符串
             * minTime:时间更新间隔，单位：ms
			 * minDistance:位置刷新距离，单位：m
			 * listener:用于定位更新的监听者locationListener
             */
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
        } else {
            Log.i(TAG, "无法定位，请打开定位提供者");
            Toast.makeText(this, "无法定位，请打开定位服务", Toast.LENGTH_SHORT).show();
            Intent i = new Intent();
            i.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(i);
        }
//        manager.requestLocationUpdates(minTime, minDistance, criteria, intent);
    }

    @Override
    public void onLocationChanged(Location location) {

        // 得到纬度
         double latitude = location.getLatitude();
//        double latitude = 29.33813;
        Log.i(TAG, "纬度 =" + latitude);
        // 得到经度
         double longitude = location.getLongitude();
//        double longitude = 117.190753;
        Log.i(TAG, "经度 =" + longitude);

        List<Address> locationList = getLocationList(latitude, longitude);
        if (!locationList.isEmpty()) {
            Address address = locationList.get(0);
            Log.i(TAG, "address =" + address);
            String countryName = address.getCountryName();
            Log.i(TAG, "countryName = " + countryName);
            String countryCode = address.getCountryCode();
            Log.i(TAG, "countryCode = " + countryCode);
            String locality = address.getLocality();
            Log.i(TAG, "locality = " + locality);
            for (int i = 0; address.getAddressLine(i) != null; i++) {
                String addressLine = address.getAddressLine(i);
                Log.i(TAG, "addressLine = " + addressLine);
            }
        }
//        // 通知Activity
//        Intent intent = new Intent();
//        intent.setAction(Common.LOCATION_ACTION);
//        intent.putExtra(Common.LOCATION, location.toString());
//        sendBroadcast(intent);
//        Log.i(TAG, "sendBroadcast");
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {}

    @Override
    public void onProviderEnabled(String provider) {}

    @Override
    public void onProviderDisabled(String provider) {}

    private List<Address> getLocationList(double latitude, double longitude) {
        Log.i(TAG, "getLocationList");
        Geocoder gc = new Geocoder(this, Locale.getDefault());
        List<Address> locationList = null;
        try {
            locationList = gc.getFromLocation(latitude, longitude, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return locationList;
    }
}
